package com.xdl.modules.system.controller;

import com.xdl.common.exception.BelugaException;
import com.xdl.common.response.ResponseResult;
import com.xdl.common.utils.StringUtils;
import com.xdl.modules.system.model.DuplicateCheckModel;
import com.xdl.modules.system.service.SysDictService;
import com.xdl.modules.utils.SqlInjectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/sys/duplicate")
public class DuplicateCheckController {

    @Autowired
    private SysDictService dictService;

    @PostMapping("check")
    public ResponseResult<?> doDuplicateCheck(@RequestBody DuplicateCheckModel model){
        final String[] sqlInjCheck = {model.getTableName(),model.getFieldName()};
        SqlInjectionUtil.filterContent(sqlInjCheck);
        if(StringUtils.isEmpty(model.getFieldVal())){
            BelugaException.fatal("数据为空,不作处理！");
        }
        Long num;
        if (StringUtils.isNotBlank(model.getDataId())) {
            // [2].编辑页面校验
            num = dictService.duplicateCheckCountSql(model);
        } else {
            // [1].添加页面校验
            num = dictService.duplicateCheckCountSqlNoDataId(model);
        }
        if (num == null || num == 0) {
            // 该值可用
            return ResponseResult.Success("校验通过！");
        } else {
            // 该值不可用
            log.info("该值不可用，系统中已存在！");
            return ResponseResult.Error("该值不可用，系统中已存在！");
        }
    }


}
